﻿using GBT.Tool.Core;
using Newtonsoft.Json.Linq;
using NLog;
using Persistence.Core;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace QueryDataLogic.Core
{
    public class SendMealMessage
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        QueryData qd = new QueryData();
        WXServiceAPI wxApi = new WXServiceAPI();
        BasicInfo bi = new BasicInfo();

        #region 得到一周的周一和周日的日期
        /// <summary>
        /// 计算本周的周一日期
        /// </summary>
        /// <returns></returns>
        public static DateTime GetMondayDate()
        {
            return GetMondayDate(DateTime.Now);
        }

        /// <summary>
        /// 计算本周周日的日期
        /// </summary>
        /// <returns></returns>
        public static DateTime GetSundayDate()
        {
            return GetSundayDate(DateTime.Now);
        }

        /// <summary>
        /// 计算某日起始日期（礼拜一的日期）
        /// </summary>
        /// <param name="someDate">该周中任意一天</param>
        /// <returns>返回礼拜一日期，后面的具体时、分、秒和传入值相等</returns>
        public static DateTime GetMondayDate(DateTime someDate)
        {
            int i = someDate.DayOfWeek - DayOfWeek.Monday;
            if (i == -1) i = 6;// i值 > = 0 ，因为枚举原因，Sunday排在最前，此时Sunday-Monday=-1，必须+7=6。
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return someDate.Subtract(ts);
        }

        /// <summary>
        /// 计算某日结束日期（礼拜日的日期）
        /// </summary>
        /// <param name="someDate">该周中任意一天</param>
        /// <returns>返回礼拜日日期，后面的具体时、分、秒和传入值相等</returns>
        public static DateTime GetSundayDate(DateTime someDate)
        {
            int i = someDate.DayOfWeek - DayOfWeek.Sunday;
            if (i != 0) i = 7 - i;// 因为枚举原因，Sunday排在最前，相减间隔要被7减。
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return someDate.Add(ts);
        }

        /// <summary>
        /// 判断是不是周末/节假日
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns>周末和节假日返回true，工作日返回false</returns>
        //public static async Task<bool> IsHolidayByDate(DateTime date)
        public static bool IsHolidayByDate(DateTime date)
        {
            var isHoliday = false;
            var webClient = new System.Net.WebClient();
            var PostVars = new System.Collections.Specialized.NameValueCollection
            {
                { "d", date.ToString("yyyyMMdd") }//参数
            };
            try
            {
                var day = date.DayOfWeek;
                //判断是否为周末
                if (day == DayOfWeek.Sunday || day == DayOfWeek.Saturday)
                    return true;
                //0为工作日，1为周末，2为法定节假日
                //var byteResult = await webClient.UploadValuesTaskAsync("http://tool.bitefu.net/jiari/", "POST", PostVars);//请求地址,传参方式,参数集合
                //var result = Encoding.UTF8.GetString(byteResult);//获取返回值
                //if (result == "1" || result == "2")
                //    isHoliday = true;
            }
            catch
            {
                isHoliday = false;
            }
            return isHoliday;
        }
        #endregion

        /// <summary>
        /// 向未报餐人员发送短信通知
        /// </summary>
        public JObject SendNotToEatMessage(JObject value)
        {
            JObject joResult = new JObject();
            try
            {
                int districtID = (int)value["districtID"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select distinct mu.UserID,mu.mobile,mu.Number,mu.Name,ISNULL(mu.OpenID,'') OpenID from MealUser mu " +
                                "left join ReportMeals rm on mu.UserID = rm.UserID and rm.Date >= CONVERT(varchar(100), DATEADD(d, 1, GETDATE()), 23) " +
                                "where ISNULL(rm.ID, 0) = 0 "
                };

                JArray ja = qd.GetData(comm, dbName);
                JObject joItem = new JObject();

                JObject joDate = new JObject();
                if (IsHolidayByDate(DateTime.Now))
                {
                    //周末时，报餐日期自动调整为下周一
                    DateTime dtNow = DateTime.Now.AddDays(2);
                    DateTime dtLastWorkDate = GetMondayDate(dtNow);
                    joDate["value"] = dtLastWorkDate.ToString("yyyy-MM-dd");
                }
                else
                {
                    joDate["value"] = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                }
                JObject joTime = new JObject();
                joTime["value"] = DateTime.Now.ToString("yyyy-MM-dd") + " 17:30:00";
                JObject joPhrase = new JObject();
                joPhrase["value"] = "请及时报餐";

                JObject joData = new JObject();
                joData["date1"] = joDate;
                joData["time2"] = joTime;
                joData["phrase3"] = joPhrase;

                JObject jo = new JObject();
                jo["template_id"] = "1L5a_xdZW3jeggkOV7N03Mbrzzg4E4Ql9OE6ZHtY-xs";
                jo["page"] = "pages/authorization/authorization";
                jo["data"] = joData;

                if (ja.Count > 0)
                {
                    if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Friday) { }//当前日期为周五或周六时 不发送报餐提醒
                    else
                    {
                        for (int jaIndex = 0; jaIndex < ja.Count; jaIndex++)
                        {
                            joItem = (JObject)ja[jaIndex];
                            jo["touser"] = (string)joItem["OpenID"];
                            //报餐提醒模板消息
                            wxApi.sendMealMessage(jo);
                        }
                    }

                    joResult["state"] = true;
                    joResult["message"] = "受影响的行数为：" + ja.Count;

                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                joResult["state"] = false;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
            }

            return joResult;
        }

    }
}
